package com.chen.tliaswebtest.controller;

import com.chen.tliaswebtest.annotation.LogOperation;
import com.chen.tliaswebtest.pojo.Dept;
import com.chen.tliaswebtest.pojo.Result;
import com.chen.tliaswebtest.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/24
 * 部门管理控制层
 */
@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    private final DeptService deptService;

    public DeptController(DeptService deptService) {
        this.deptService = deptService;
    }

    // 查询所有部门
    @GetMapping
    public Result list() {
        return Result.success(deptService.list());
    }

    // 根据部门ID查询
    @GetMapping("/{id}")
    public Result getDeptById(@PathVariable Integer id) {
        return Result.success(deptService.getDeptById(id));
    }

    // 添加部门数据
    @PostMapping
    @LogOperation
    public Result addDept(@RequestBody Dept dept) {
        if (checkRequired(dept.getName())) {
            String message = "必须项目name不能为null";
            log.error(message);
            return Result.error(message);
        }
        deptService.addDept(dept);
        return Result.success();
    }

    // 根据ID删除部门数据
    @DeleteMapping
    @LogOperation
    public Result deleteDept(@RequestParam("id") Integer id) {
        deptService.removeDeptById(id);
        return Result.success();
    }

    // 修改部门数据
    @PutMapping
    @LogOperation
    public Result updateDept(@RequestBody Dept dept) {
        if (checkRequired(dept.getId())) {
            return Result.error("必须项目id不能为null");
        }
        if (checkRequired(dept.getName())) {
            return Result.error("必须项目name不能为null");
        }
        deptService.updateDept(dept);
        return Result.success();
    }

    // 必须项目check
    private boolean checkRequired(Object obj) {
        return !Objects.nonNull(obj);
    }
}
